<template>
	<up-popup :show="show" @close="show = false" :safeAreaInsetBottom="false" mode="center" :closeOnClickOverlay="false"
		:round="16">
		<view class="uu-privacy-popup">
			<view class="uu-privacy-popup__header">
				<view class="uu-picker__title">隐私保护指引</view>
			</view>
			<view class="uu-privacy-popup__container">
				<view>
					感谢选择我们的小程序，我们非常重视您的个人信息安全和隐私保护。根据最新法律要求，使用我们的产品前，请仔细阅读“
					<text class="uu-privacy-popup__container-protocol" @click="openPrivacyContract" :style="{
              color: color,
            }">{{ `《${appName}小程序隐私保护指引》` }}</text>”，以便我们向您提供更优质的服务!
				</view>
				<text>我们将尽全力保护您的个人信息及合法权益，感谢您的信任!</text>
			</view>
			<view class="uu-privacy-popup__footer">
				<button class="is-disagree" id="disagree-btn" @click="handleDisagree">
					拒绝
				</button>
				<button :style="{
            background: color,
          }" class="is-agree" id="agree-btn" open-type="agreePrivacyAuthorization"
					@agreeprivacyauthorization="handleAgree">
					同意
				</button>
			</view>
		</view>
	</up-popup>
</template>

<script setup lang="ts">
	import { nextTick, onMounted, ref } from "vue";

	/**
	 * @property {String}	appName 必传|小程序名
	 * @property {Boolean}	manual	是否手动监听需要授权，true-执行情况一，false执行情况二
	 * @property {Boolean}	isExit	拒绝授权是否直接退出小程序
	 * @property {String}	color	主题色（默认#5685ff）
	 */
	const $props = withDefaults(
		defineProps<{
			manual ?: boolean;
			isExit ?: boolean;
			color ?: string;
			appName : "";
		}>(),
		{
			isExit: false,
			color: "#5685ff",
		}
	);

	/**
	 * @event disagree 拒绝授权执行事件
	 * @event agree 同意授权执行事件
	 */
	const $emit = defineEmits<{
		(e : "disagree") : void;
		(e : "agree") : void;
	}>();

	const privacyResolves = new Set();
	let privacyHandler : any = null;
	const show = ref(false);

	/**
	 * @description 情况一.注册监听需要授权
	 * 一般在需要点击授权的按钮时自动弹出隐私协议（比如登录）
	 */
	if (wx.onNeedPrivacyAuthorization) {
		wx.onNeedPrivacyAuthorization((resolve : any) => {
			console.log(resolve, "resolve");
			if (typeof privacyHandler === "function") {
				privacyHandler(resolve);
			}
		});
	}

	/**
	 * @description 情况二.查询隐私授权情况
	 * 一般在小程序启动时自动弹出隐私协议（比如启动时需要授权获取定位等，授权后登录等则不需要再次授权）
	 */
	if (wx.getPrivacySetting && !$props.manual) {
		wx.getPrivacySetting({
			success: (res : any) => {
				if (res.needAuthorization) {
					if (typeof privacyHandler === "function") {
						privacyHandler();
					}
				} else {
					$emit("agree");
				}
			},
			fail: () => { },
			complete: () => { },
		});
	}

	const openPrivacyContract = () => {
		wx.openPrivacyContract({
			success: (res : any) => {
				console.log("openPrivacyContract success");
			},
			fail: (res : any) => {
				console.error("openPrivacyContract fail", res);
			},
		});
	};

	// 拒绝
	const handleDisagree = () => {
		show.value = false;
		if ($props.manual) {
			privacyResolves.forEach((resolve : any) => {
				resolve({
					event: "disagree",
				});
			});
			privacyResolves.clear();

			$emit("disagree");
		}

		// #ifdef MP
		if ($props.isExit) wx.exitMiniProgram();
		// #endif
	};

	// 同意
	const handleAgree = () => {
		show.value = false;
		if ($props.manual) {
			privacyResolves.forEach((resolve : any) => {
				resolve({
					event: "agree",
					buttonId: "agree-btn",
				});
			});
			privacyResolves.clear();
		}
		$emit("agree");
	};

	const getPrevPage = (num = 1) => {
		let pages = getCurrentPages();
		let currentPage = pages[pages.length - num];
		return new Promise((resolve, reject) => {
			if (currentPage) {
				resolve(currentPage);
			} else {
				reject("页面不存在");
			}
		});
	};

	const getComponent = (context, selector) => {
		let component = null;
		// #ifdef MP-WEIXIN
		component =
			context.selectComponent &&
			context.selectComponent(selector) &&
			context.selectComponent(selector).$vm;
		// #endif

		return component;
	};

	onMounted(() => {
		privacyHandler = async (resolve : any) => {
			const context = await getPrevPage();
			const privacyPopup = getComponent(context, "#uu-privacy");
			if (privacyPopup) {
				nextTick(() => {
					show.value = true;
				});
			}

			privacyResolves.add(resolve);
		};
	});
</script>

<style scoped lang="scss">
	.uu-privacy-popup {
		padding: 40rpx 40rpx 60rpx;
		width: 640rpx;
		box-sizing: border-box;
		overflow: hidden;

		&__header {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 52rpx;
			font-size: 34rpx;
			font-weight: 550;
			color: #1a1a1a;
			line-height: 52rpx;
			margin-bottom: 40rpx;
		}

		&__container {
			width: 100%;
			box-sizing: border-box;
			font-size: 28rpx;
			font-weight: 400;
			color: #333333;
			line-height: 42rpx;
			margin-bottom: 48rpx;
			text-align: justify;

			&-protocol {
				font-weight: 550;
			}
		}

		&__footer {
			display: flex;
			align-items: center;
			justify-content: space-between;

			button {
				border: none;
				outline: none;

				&::after {
					border: none;
				}
			}

			.is-disagree,
			.is-agree {
				height: 80rpx;
				font-size: 32rpx;
				font-weight: 400;
				color: #666666;
			}

			.is-disagree {
				width: calc(40% - 20rpx);
				border: 1rpx solid #eee;
			}

			.is-agree {
				width: calc(60% - 20rpx);
				color: #ffffff;
			}
		}
	}
</style>